package com.dream.wukong.configcenter.client.core.util;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.Objects;
import java.util.Set;

/**
* 描  述: 静态工具类
* 创建时间: 2018/5/23
*/
public class ConfigConstant {
    private static Logger logger = Logger.getLogger(ConfigConstant.class);
    public static final String HTTP_PROTOCOL = "http://";
    public static final String COLON = ":";
    public static final String SLASH = "/";
    public static final String CONFIG = "/configs/";
    public static final String DEFAULT_CONFIG = "/configcenter-manager/configs/default/";
    public static final String DEFAULT_SERVICE_NAME = "default";
    public static final String DEFAULT_CONFIG_IP = "127.0.0.1";
    public static final String DEFAULT_CONFIG_PORT = "80";



    /***
    * 描  述: 获取服务名称    如jdbc redis   目前接口返回的串为  名称/ID
    * 参  数:urlStr
    * 参  数:defaultUrl
    * 参  数:serviceUrl
    * 返回值: java.lang.String
    * 创建时间: 2018/5/25
    */
    public static String getServiceName(String urlStr,String defaultUrl,String serviceUrl) {
        String sourceName = urlStr;
        if(StringUtils.isNotBlank(urlStr) && StringUtils.isNotBlank(defaultUrl) && StringUtils.isNotBlank(serviceUrl)){

           urlStr = urlStr.replace(defaultUrl,"");
           urlStr = urlStr.replace(serviceUrl,"");

           String[] splits = urlStr.split(SLASH);
           sourceName =  splits[0];
       }
        return sourceName;
    }

    /***
    * 描  述: 将json配置串存储到系统环境变量
    * 参  数:jsonStr
    * 返回值: void
    * 创建时间: 2018/5/25
    */
    public static void pushPropertyToSystem(String jsonStr){

        JSONObject configValueJson = null;
        try {
            configValueJson = JSONObject.parseObject(jsonStr);
        } catch (Exception e) {
            logger.error("转换json出错 : " ,e);
        }
        if(!Objects.isNull(configValueJson)){
            Set<String> keys = configValueJson.keySet();
            if(CollectionUtils.isNotEmpty(keys)){
                for( String key : keys){
                    System.setProperty(key,configValueJson.getString(key).toString());
                }
            }
        }

    }
}
